// 改进的Markdown解析器
export class MarkdownParser {
  private static escapeHtml(text: string): string {
    const div = document.createElement('div')
    div.textContent = text
    return div.innerHTML
  }

  private static parseInlineElements(text: string): string {
    // 先处理代码块，避免其他格式化影响代码内容
    text = text.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
    
    // 处理粗体（**text** 或 __text__）
    text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    text = text.replace(/__([^_]+)__/g, '<strong>$1</strong>')
    
    // 处理斜体（*text* 或 _text_）
    text = text.replace(/\*([^*]+)\*/g, '<em>$1</em>')
    text = text.replace(/_([^_]+)_/g, '<em>$1</em>')
    
    // 处理删除线
    text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>')
    
    // 处理链接
    text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" class="text-blue-600 hover:text-blue-800 underline">$1</a>')
    
    // 处理图片
    text = text.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" class="max-w-full h-auto rounded-lg shadow-sm my-4" />')
    
    return text
  }

  private static parseCodeBlock(content: string): string {
    return content.replace(/```(\w+)?\n?([\s\S]*?)```/g, (match, language, code) => {
      const lang = language || 'text'
      const escapedCode = this.escapeHtml(code.trim())
      return `<pre class="code-block bg-gray-100 dark:bg-gray-800 rounded-lg p-4 overflow-x-auto my-4"><code class="language-${lang} text-sm font-mono">${escapedCode}</code></pre>`
    })
  }

  private static parseTable(content: string): string {
    const lines = content.split('\n')
    let inTable = false
    let tableRows: string[] = []
    let result: string[] = []
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim()
      
      if (line.includes('|') && line.split('|').length > 2) {
        if (!inTable) {
          inTable = true
          tableRows = []
        }
        tableRows.push(line)
      } else {
        if (inTable) {
          // 处理表格
          result.push(this.renderTable(tableRows))
          inTable = false
          tableRows = []
        }
        result.push(line)
      }
    }
    
    if (inTable && tableRows.length > 0) {
      result.push(this.renderTable(tableRows))
    }
    
    return result.join('\n')
  }

  private static renderTable(rows: string[]): string {
    if (rows.length < 2) return rows.join('\n')
    
    let html = '<table class="table-auto w-full border-collapse border border-gray-300 dark:border-gray-600 my-4">\n'
    
    // 处理表头
    const headerCells = rows[0].split('|').filter(cell => cell.trim()).map(cell => cell.trim())
    html += '<thead class="bg-gray-50 dark:bg-gray-700">\n<tr>\n'
    headerCells.forEach(cell => {
      html += `<th class="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left font-semibold">${this.parseInlineElements(cell)}</th>\n`
    })
    html += '</tr>\n</thead>\n'
    
    // 跳过分隔行，处理数据行
    html += '<tbody>\n'
    for (let i = 2; i < rows.length; i++) {
      const cells = rows[i].split('|').filter(cell => cell.trim()).map(cell => cell.trim())
      if (cells.length > 0) {
        html += '<tr class="hover:bg-gray-50 dark:hover:bg-gray-800">\n'
        cells.forEach(cell => {
          html += `<td class="border border-gray-300 dark:border-gray-600 px-4 py-2">${this.parseInlineElements(cell)}</td>\n`
        })
        html += '</tr>\n'
      }
    }
    html += '</tbody>\n</table>'
    
    return html
  }

  private static parseList(content: string): string {
    const lines = content.split('\n')
    let result: string[] = []
    let inList = false
    let listItems: string[] = []
    let listType = 'ul' // 'ul' for unordered, 'ol' for ordered
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i]
      const trimmedLine = line.trim()
      
      // 检查是否是列表项
      const unorderedMatch = trimmedLine.match(/^[-*+]\s+(.+)/)
      const orderedMatch = trimmedLine.match(/^\d+\.\s+(.+)/)
      const taskMatch = trimmedLine.match(/^[-*+]\s+\[([ x])\]\s+(.+)/)
      
      if (unorderedMatch || orderedMatch || taskMatch) {
        if (!inList) {
          inList = true
          listItems = []
          listType = orderedMatch ? 'ol' : 'ul'
        }
        
        if (taskMatch) {
          const checked = taskMatch[1] === 'x'
          const taskText = taskMatch[2]
          listItems.push(`<li class="flex items-center space-x-2"><input type="checkbox" ${checked ? 'checked' : ''} disabled class="rounded"><span class="${checked ? 'line-through text-gray-500' : ''}">${this.parseInlineElements(taskText)}</span></li>`)
        } else {
          const text = unorderedMatch ? unorderedMatch[1] : orderedMatch![1]
          listItems.push(`<li class="mb-1">${this.parseInlineElements(text)}</li>`)
        }
      } else {
        if (inList) {
          // 结束当前列表
          const listClass = listType === 'ul' ? 'list-disc list-inside space-y-1 my-4 ml-4' : 'list-decimal list-inside space-y-1 my-4 ml-4'
          result.push(`<${listType} class="${listClass}">\n${listItems.join('\n')}\n</${listType}>`)
          inList = false
          listItems = []
        }
        result.push(line)
      }
    }
    
    // 处理最后的列表
    if (inList && listItems.length > 0) {
      const listClass = listType === 'ul' ? 'list-disc list-inside space-y-1 my-4 ml-4' : 'list-decimal list-inside space-y-1 my-4 ml-4'
      result.push(`<${listType} class="${listClass}">\n${listItems.join('\n')}\n</${listType}>`)
    }
    
    return result.join('\n')
  }

  private static parseBlockquote(content: string): string {
    return content.replace(/^>\s*(.+)$/gm, '<blockquote class="border-l-4 border-gray-300 dark:border-gray-600 pl-4 py-2 my-4 bg-gray-50 dark:bg-gray-800 italic">$1</blockquote>')
  }

  private static parseHeadings(content: string): string {
    // H6
    content = content.replace(/^######\s+(.+)$/gm, '<h6 class="text-sm font-semibold text-gray-900 dark:text-gray-100 mt-6 mb-3">$1</h6>')
    // H5
    content = content.replace(/^#####\s+(.+)$/gm, '<h5 class="text-base font-semibold text-gray-900 dark:text-gray-100 mt-6 mb-3">$1</h5>')
    // H4
    content = content.replace(/^####\s+(.+)$/gm, '<h4 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mt-6 mb-3">$1</h4>')
    // H3
    content = content.replace(/^###\s+(.+)$/gm, '<h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100 mt-8 mb-4">$1</h3>')
    // H2
    content = content.replace(/^##\s+(.+)$/gm, '<h2 class="text-2xl font-semibold text-gray-900 dark:text-gray-100 mt-10 mb-4 border-b border-gray-200 dark:border-gray-700 pb-2">$1</h2>')
    // H1
    content = content.replace(/^#\s+(.+)$/gm, '<h1 class="text-3xl font-bold text-gray-900 dark:text-gray-100 mt-8 mb-6 border-b-2 border-gray-200 dark:border-gray-700 pb-3">$1</h1>')
    
    return content
  }

  private static parseHorizontalRule(content: string): string {
    return content.replace(/^(-{3,}|\*{3,}|_{3,})$/gm, '<hr class="border-t-2 border-gray-200 dark:border-gray-700 my-8">')
  }

  private static parseParagraphs(content: string): string {
    // 将连续的非空行合并为段落
    const lines = content.split('\n')
    let result: string[] = []
    let currentParagraph: string[] = []
    
    for (const line of lines) {
      const trimmedLine = line.trim()
      
      // 如果是空行或已经是HTML标签，结束当前段落
      if (!trimmedLine || trimmedLine.startsWith('<')) {
        if (currentParagraph.length > 0) {
          const paragraphText = currentParagraph.join(' ').trim()
          if (paragraphText) {
            result.push(`<p class="mb-4 leading-relaxed text-gray-700 dark:text-gray-300">${this.parseInlineElements(paragraphText)}</p>`)
          }
          currentParagraph = []
        }
        if (trimmedLine) {
          result.push(line)
        }
      } else {
        currentParagraph.push(trimmedLine)
      }
    }
    
    // 处理最后的段落
    if (currentParagraph.length > 0) {
      const paragraphText = currentParagraph.join(' ').trim()
      if (paragraphText) {
        result.push(`<p class="mb-4 leading-relaxed text-gray-700 dark:text-gray-300">${this.parseInlineElements(paragraphText)}</p>`)
      }
    }
    
    return result.join('\n')
  }

  public static parse(markdown: string): string {
    if (!markdown.trim()) return ''
    
    let content = markdown
    
    // 1. 首先处理代码块（避免其他解析影响代码内容）
    content = this.parseCodeBlock(content)
    
    // 2. 处理表格
    content = this.parseTable(content)
    
    // 3. 处理列表
    content = this.parseList(content)
    
    // 4. 处理引用
    content = this.parseBlockquote(content)
    
    // 5. 处理标题
    content = this.parseHeadings(content)
    
    // 6. 处理水平分割线
    content = this.parseHorizontalRule(content)
    
    // 7. 最后处理段落（这会处理剩余的内联元素）
    content = this.parseParagraphs(content)
    
    return content
  }
}